<template>
  <div class="super-agent-container">
    <div class="header">
      <div class="back-button" @click="goBack">返回</div>
      <h1 class="title">AI超级智能体</h1>
      <div class="placeholder"></div>
    </div>
    
    <div class="content-wrapper">
      <div class="chat-area">
        <ChatRoom 
          :messages="messages" 
          :connection-status="connectionStatus"
          ai-type="super"
          @send-message="sendMessage"
        />
      </div>
    </div>
    
    <div class="footer-container">
      <AppFooter />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useHead } from '@vueuse/head'
import ChatRoom from '../components/ChatRoom.vue'
import AppFooter from '../components/AppFooter.vue'
import { chatWithManus } from '../api'

// 设置页面标题和元数据
useHead({
  title: 'AI超级智能体 - AI超级智能体应用平台',
  meta: [
    {
      name: 'description',
      content: 'AI超级智能体是AI超级智能体应用平台的全能助手，能解答各类专业问题，提供精准建议和解决方案'
    },
    {
      name: 'keywords',
      content: 'AI超级智能体,智能助手,专业问答,AI问答,专业建议,AI智能体'
    }
  ]
})

const router = useRouter()
const messages = ref([])
const connectionStatus = ref('disconnected')
let eventSource = null

// 添加消息到列表
const addMessage = (content, isUser, type = '') => {
  messages.value.push({
    content,
    isUser,
    type,
    time: new Date().getTime()
  })
}

// 发送消息
const sendMessage = (message) => {
  addMessage(message, true, 'user-question')
  
  // 连接SSE
  if (eventSource) {
    eventSource.close()
  }
  
  // 设置连接状态
  connectionStatus.value = 'connecting'
  
  // 临时存储
  let messageBuffer = []; // 用于存储SSE消息的缓冲区
  let lastBubbleTime = Date.now(); // 上一个气泡的创建时间
  let isFirstResponse = true; // 是否是第一次响应
  
  const chineseEndPunctuation = ['。', '！', '？', '…']; // 中文句子结束标点
  const minBubbleInterval = 800; // 气泡最小间隔时间(毫秒)
  
  // 创建消息气泡的函数
  const createBubble = (content, type = 'ai-answer') => {
    if (!content.trim()) return;
    
    // 添加适当的延迟，使消息显示更自然
    const now = Date.now();
    const timeSinceLastBubble = now - lastBubbleTime;
    
    if (isFirstResponse) {
      // 第一条消息立即显示
      addMessage(content, false, type);
      isFirstResponse = false;
    } else if (timeSinceLastBubble < minBubbleInterval) {
      // 如果与上一气泡间隔太短，添加一个延迟
      setTimeout(() => {
        addMessage(content, false, type);
      }, minBubbleInterval - timeSinceLastBubble);
    } else {
      // 正常添加消息
      addMessage(content, false, type);
    }
    
    lastBubbleTime = now;
    messageBuffer = []; // 清空缓冲区
  };
  
  eventSource = chatWithManus(message)
  
  // 监听SSE消息
  eventSource.onmessage = (event) => {
    const data = event.data
    
    if (data && data !== '[DONE]') {
      messageBuffer.push(data);
      
      // 检查是否应该创建新气泡
      const combinedText = messageBuffer.join('');
      
      // 句子结束或消息长度达到阈值
      const lastChar = data.charAt(data.length - 1);
      const hasCompleteSentence = chineseEndPunctuation.includes(lastChar) || data.includes('\n\n');
      const isLongEnough = combinedText.length > 40;
      
      if (hasCompleteSentence || isLongEnough) {
        createBubble(combinedText);
      }
    }
    
    if (data === '[DONE]') {
      // 如果还有未显示的内容，创建最后一个气泡
      if (messageBuffer.length > 0) {
        const remainingContent = messageBuffer.join('');
        createBubble(remainingContent, 'ai-final');
      }
      
      // 完成后关闭连接
      connectionStatus.value = 'disconnected'
      eventSource.close()
    }
  }
  
  // 监听SSE错误
  eventSource.onerror = (error) => {
    console.error('SSE Error:', error)
    connectionStatus.value = 'error'
    eventSource.close()
    
    // 如果出错时有未显示的内容，也创建气泡
    if (messageBuffer.length > 0) {
      const remainingContent = messageBuffer.join('');
      createBubble(remainingContent, 'ai-error');
    }
  }
}

// 返回主页
const goBack = () => {
  router.push('/')
}

// 页面加载时添加欢迎消息
onMounted(() => {
  // 添加欢迎消息
  addMessage('你好，我是AI超级智能体。我可以解答各类问题，提供专业建议，请问有什么可以帮助你的吗？', false)
})

// 组件销毁前关闭SSE连接
onBeforeUnmount(() => {
  if (eventSource) {
    eventSource.close()
  }
})
</script>

<style scoped>
.super-agent-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  /* 渐变背景 */
  background: linear-gradient(135deg, #e0eaff 0%, #f9fbff 100%);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 32px;
  background: linear-gradient(90deg, #3f51b5 0%, #5c6bc0 100%);
  color: white;
  box-shadow: 0 4px 16px rgba(63, 81, 181, 0.15);
  border-bottom-left-radius: 24px;
  border-bottom-right-radius: 24px;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-button {
  font-size: 18px;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 8px 16px;
  border-radius: 20px;
  background: rgba(255,255,255,0.15);
  transition: background 0.2s, box-shadow 0.2s;
  box-shadow: 0 2px 8px rgba(63, 81, 181, 0.08);
  border: none;
  outline: none;
}

.back-button:hover {
  background: rgba(255,255,255,0.25);
  box-shadow: 0 4px 16px rgba(63, 81, 181, 0.15);
}

.back-button:before {
  content: '←';
  margin-right: 8px;
}

.title {
  font-size: 28px;
  font-weight: 800;
  margin: 0;
  letter-spacing: 1px;
  text-shadow: 0 2px 8px rgba(63, 81, 181, 0.08);
}

.placeholder {
  width: 1px;
  visibility: hidden;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  flex: 1;
  align-items: center;
  justify-content: center;
}

.chat-area {
  width: 100%;
  max-width: 600px;
  flex: 1;
  padding: 32px 20px 24px 20px;
  background: rgba(255,255,255,0.85);
  border-radius: 24px;
  box-shadow: 0 8px 32px rgba(63, 81, 181, 0.10);
  margin: 32px 0 24px 0;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  transition: box-shadow 0.2s;
}

.chat-area:hover {
  box-shadow: 0 12px 40px rgba(63, 81, 181, 0.18);
}

.footer-container {
  margin-top: auto;
  padding-bottom: 12px;
}

/* 响应式样式 */
@media (max-width: 900px) {
  .chat-area {
    max-width: 98vw;
    padding: 20px 4vw 16px 4vw;
    margin: 20px 0 16px 0;
    min-height: 320px;
  }
  .header {
    padding: 14px 10vw;
    border-bottom-left-radius: 16px;
    border-bottom-right-radius: 16px;
  }
}

@media (max-width: 600px) {
  .header {
    padding: 10px 4vw;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
  }
  .title {
    font-size: 20px;
  }
  .chat-area {
    padding: 10px 2vw 10px 2vw;
    border-radius: 10px;
    margin: 10px 0 8px 0;
    min-height: 180px;
  }
  .back-button {
    font-size: 15px;
    padding: 6px 10px;
    border-radius: 14px;
  }
}

@media (max-width: 400px) {
  .header {
    padding: 6px 2vw;
  }
  .title {
    font-size: 16px;
  }
  .chat-area {
    padding: 4px 1vw 4px 1vw;
    min-height: 100px;
  }
}
</style> 